package com.self.campussecondhandmarket.controller.user;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.self.campussecondhandmarket.common.BaseContext;
import com.self.campussecondhandmarket.content.ImageContent;
import com.self.campussecondhandmarket.entity.domain.User;
import com.self.campussecondhandmarket.entity.request.user.LoginReq;
import com.self.campussecondhandmarket.entity.request.user.Register;
import com.self.campussecondhandmarket.resp.Result;
import com.self.campussecondhandmarket.service.UserService;
import com.self.campussecondhandmarket.utils.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "http://localhost:9999", allowCredentials = "true")
public class UserController {
	
	@Autowired
	UserService userService;
	
	/**
	 * 登录
	 *
	 * @param dto 登录参数
	 */
	@PostMapping("/login")
	public Result login(@RequestBody @NonNull LoginReq dto) {
		log.info("进入到user --> login");
		User one = userService.getOne(Wrappers.<User>lambdaQuery()
				.eq(User::getPhone, dto.getPhone())
				.eq(User::getPassword, dto.getPassword())
		);
		
		if (one == null) {
			return Result.error("用户名或密码错误");
		}
		one.setToken(JWTUtil.generateToken(Map.of("id", one.getId())));
		return Result.success(one);
	}
	
	/**
	 * 查询手机号是否注册
	 *
	 * @param phone 手机号
	 */
	@GetMapping("/getPhone")
	public Result getPhone(@RequestParam @NonNull String phone) {
		log.info("进入到user --> getPhone");
		User one = userService.getOne(Wrappers.<User>lambdaQuery()
				.eq(User::getPhone, phone)
		);
		if (one != null) {
			return Result.error("手机号已注册");
		}
		return Result.success();
	}
	
	
	@PostMapping("/register")
	public Result register(@RequestBody @NonNull Register dto) {
		log.info("进入到user --> register");
		if (dto.getPhone().length() != 11) {
			return Result.error("手机号格式错误");
		}
		User user = new User();
		BeanUtils.copyProperties(dto, user);
		userService.save(user);
		return Result.success();
	}
	
	
	@PostMapping("/edit")
	@Transactional
	public Result edit(MultipartFile file, HttpServletRequest request) throws IOException {
		log.info("进入到user --> edit");
		String fileName = file.getOriginalFilename();
		User user = userService.getById(BaseContext.getId());
		if (user == null) {
			return Result.error("用户不存在");
		}
		user.setAvatarUrl(ImageContent.AVATAR_IMAGE_INTERNET_PATH + fileName);
		user.setName(request.getParameter("name"));
		userService.updateById(user);
		byte[] bytes = file.getBytes();
		try (FileOutputStream fileOutputStream = new FileOutputStream(ImageContent.AVATAR_IMAGE_FILE_PATH + fileName)) {
			fileOutputStream.write(bytes);
		}
		return Result.success("修改成功");
	}
	
	
	@PostMapping("/admin/all")
	public Result adminAll() {
		log.info("进入到user --> adminAll");
		return Result.success(userService.list());
	}
	
	@PostMapping("/admin/add")
	public Result adminAdd(@RequestBody @NonNull User user) {
		log.info("进入到user --> adminAdd");
		if (this.getPhone(user.getPhone()).getCode() != 200) {
			return Result.error("手机号已注册");
		}
		userService.save(user);
		return Result.success("注册成功");
	}
	
	@PostMapping("/admin/edit")
	public Result adminEdit(@RequestBody @NonNull User user) {
		log.info("进入到user --> adminEdit");
		user.setUpdateTime(null);
		userService.updateById(user);
		return Result.success("修改成功");
	}
	
	@PostMapping("/admin/del/{id}")
	public Result adminDel(@PathVariable Integer id) {
		log.info("进入到user --> adminDel");
		userService.removeById(id);
		return Result.success("删除成功");
	}
	
	@PostMapping("/admin/filter")
	public Result adminFilter(@RequestBody @NonNull User user) {
		log.info("进入到user --> adminFilter");
		return Result.success(userService.list(Wrappers.<User>lambdaQuery()
				.eq(user.getName() != null, User::getName, user.getName())
				.eq(user.getPhone() != null, User::getPhone, user.getPhone())
				.eq(user.getPassword() != null, User::getPassword, user.getPassword())
		));
	}
	
}